#include "comm.h"
int main()
{
  umask(0);
  if(-1 == mkfifo(FIFO_FILE, 0644)){
    perror("mkfifo");
    return 1;
  }
  int fd = open(FIFO_FILE, O_RDONLY);
  if(fd < 0){
    perror("open error");
    return 2;
  }
  //else if(fd >= 0){
    char buf[64];//读的缓冲区
    while(1){
      buf[0]=0;//字符串清空
      ssize_t s = read(fd, buf, sizeof(buf)-1);//sizeof(buf)-1是期望读取多少内容
      if(s > 0){//success read 
        buf[s] = 0;//最后添加结束标志
        printf("client# %s\n", buf);
        char *p = buf; //分析输入内存
        const char *lable = "+-*/%";
        int flag = 0;
        while(*p){ 
          switch(*p){
            case '+':flag = 0;
              break;
            case '-':flag = 1;
              break;
            case '*':flag = 2;
              break;
            case '/':flag = 3;
              break;
            case '%':flag = 4;
              break;
          }
          p++;
        }
        char *data1 = strtok(buf, "+-*/%");
        char *data2 = strtok(NULL, "+-*/%");
        int x = atoi(data1);
        int y = atoi(data2);
        int z = 0;
        switch(flag){
            case 0: z = x + y;
              break;
            case 1: z = x - y;
              break;
            case 2: z = x * y;
              break;
            case 3: z = x / y;
              break;
            case 4: z = x % y;
              break;
        }
        printf("%d %c %d = %d\n", x, *(lable+flag), y, z);
        //printf("%d %c %d = %d\n", x, lable[flag], y, z);
      }
      else if(0 == s){//对方关闭
        printf("client quit, me quit  too\n");//文件关闭了
        break;
      }
      else{
        perror("read error");
        break;
      }
    }
  //}
  close (fd);
  return 0;
}
